package com.hrm.company.controller;

import com.hrm.common.controller.BaseController;
import com.hrm.common.entity.Result;
import com.hrm.common.entity.ResultCode;
import com.hrm.company.service.CompanyService;
import com.hrm.company.service.DepartmentService;
import com.hrm.domain.company.Company;
import com.hrm.domain.company.Department;
import com.hrm.domain.company.response.DeptListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping(value = "/company") //company/department
public class DepartmentController extends BaseController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private CompanyService companyService;

    /**
     * 保存部门
     */
    @RequestMapping(value = "/department", method = RequestMethod.POST)
    public Result addDepartment(@RequestBody Department department) {
        department.setCompanyId(companyId);
        departmentService.addDepartment(department);
        //响应结果
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 更新部门
     */
    @RequestMapping(value = "/department/{id}", method = RequestMethod.PUT)
    public Result updateDepartment(@PathVariable(value = "id") String id, @RequestBody Department department) {
        department.setId(id);
        departmentService.updateDepartment(department);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * id查找部门
     */
    @RequestMapping(value = "/department/{id}", method = RequestMethod.GET)
    public Result findDepartmentById(@PathVariable(value = "id") String id) {
        Department department = departmentService.findDepartmentById(id);
        return new Result(ResultCode.SUCCESS, department);
    }

    /**
     * 查找部门列表
     */
    @RequestMapping(value = "/department", method = RequestMethod.GET)
    public Result findDepartments() {
        List<Department> departments = departmentService.findDepartments(companyId);
        //响应结果
        Company company = companyService.findCompanyById(companyId);
        return new Result(ResultCode.SUCCESS, new DeptListResult(company, departments));
    }

    /**
     * id删除部门
     */
    @RequestMapping(value = "/department/{id}", method = RequestMethod.DELETE)
    public Result deleteCompany(@PathVariable(value = "id") String id) {
        departmentService.deleteDepartment(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据code和companyId查找部门
     */
    @RequestMapping(value = "/department/search", method = RequestMethod.POST)
    public Department findByCodeAndCompanyId(@RequestParam(name = "code") String code, @RequestParam(name = "companyId") String companyId) {
        return departmentService.findByCodeAndCompanyId(code, companyId);
    }
}
